package com.example.demo.mvvm.net;

import android.content.Context;

import com.example.demo.mvvm.bean.BaseDto;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by littlehu on 2018/5/16.
 */

public abstract class BaseObserver<T>  implements Observer<BaseDto<T>>{
    private RefreshLayout refreshLayout;
    private Context mContext;
    private final String TAG = BaseObserver.class.getSimpleName();

    public BaseObserver(Context context , RefreshLayout refreshLayout , boolean isShow){
        this.mContext = context;
        this.refreshLayout = refreshLayout;
    }

    public BaseObserver(Context context , boolean isShow){
        this.mContext = context;
    }

    public abstract void onSuccess(T t , RefreshLayout refreshLayout);

    public abstract void onFailure(int code, String message ,RefreshLayout refreshLayout);


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseDto<T> tBaseDto) {
        if(tBaseDto.getErrorCode() == 0){
            onSuccess(tBaseDto.getData() , refreshLayout);
            if(refreshLayout != null) {
                refreshLayout.finishRefresh(true);
                refreshLayout.finishLoadmore(true);
            }
        }else{
            onFailure(tBaseDto.getErrorCode() , tBaseDto.getErrorMsg() , refreshLayout);
            if(refreshLayout != null) {
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadmore(false);
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        onFailure( -1 , e.getMessage() , refreshLayout);
        if(refreshLayout != null) {
            refreshLayout.finishRefresh(false);
            refreshLayout.finishLoadmore(false);
        }
    }

    @Override
    public void onComplete() {

    }
}
